package org.example.ui.log_registration;

import org.apache.commons.mail2.core.EmailException;
import org.apache.commons.mail2.jakarta.SimpleEmail;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;

public class VerificationCode {
    private static final String NAME = "zymwppt@qq.com",
    PASSWORD = "kawvbosbujpbbdid";
    private String code = "";
    public VerificationCode() {

    }

    public void sendCode(String to) throws EmailException {
        createCode();
        SimpleEmail email = new SimpleEmail();
        email.setHostName("smtp.qq.com");
        email.setSmtpPort(587);
        email.setStartTLSEnabled(true);
        email.setAuthentication(NAME, PASSWORD);
        email.setFrom(NAME);
        email.addTo(to);
        email.setSubject("验证码");
        email.setMsg(code);
        String s = email.send();
    }

    public void createCode() {
        SecureRandom random = null;
        try {
            random = SecureRandom.getInstance("SHA1PRNG", "SUN");
            code = "";
            for(int i = 0; i < 6; i++){
                code = String.format("%s%d", code, random.nextInt(10));
            }
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
    }
    public String getCode(){
        return code;
    }
}
